package Trie;

import java.util.TreeMap;

/**
 * @author shy_black
 * @date 2019/4/26 14:15
 * @Description:
 */
public class Trie {
    private class Node {
        public boolean isWord;
        public TreeMap<Character, Node> next;

        public Node(boolean isWord) {
            this.isWord = isWord;
            next = new TreeMap<>();
        }

        public Node() {
            this(false);
        }
    }

    private Node root;
    private int size;

    //获取字典的数量
    public int size() {
        root = new Node();
        return size;
    }

    //向字典中添加单词
    public void add(String word) {
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            //如果当前字符不在Trie树中，新建一个节点
            if (cur.next.get(c) == null)
                cur.next.put(c, new Node());
            //刚才创建了节点，所以现在节点一定存在，也已经被遍历过了
            //cur移动到节点c，进行新一轮遍历
            cur = cur.next.get(c);
        }
        if (!cur.isWord) {
            cur.isWord = true;
            size++;
        }
    }

    //查看单词word是否在Trie中
    public boolean contains(String word) {
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (cur.next.get(c) == null)
                return false;
            cur = cur.next.get(c);
        }
        return cur.isWord;
    }
    //查询是否在Trie中有单词以prefix为前缀
    //eg:查询char（prefix）是否为cahrater（待查单词）的前缀
    public boolean isPrefix(String prefix) {
        Node cur = root;
        for(int i = 0;i < prefix.length();i++) {
            char c = prefix.charAt(i);
            if(cur.next.get(c) == null)
                return false;
            cur = cur.next.get(c);
        }
        return true;
    }

}

















